import tkinter as tk
import tkinter.ttk as ttk
from tkinter.simpledialog import Dialog


class CustomDialog(Dialog):
    def __init__(self, parent, title="自定义对话框"):
        # 初始化变量存储用户输入
        self.name = ""
        self.age = ""
        super().__init__(parent, title)

    def body(self, master):
        """构建对话框主体内容"""
        # 设置ttk样式
        style = ttk.Style()
        style.configure("TLabel", font=("SimHei", 10))
        style.configure("TEntry", padding=5)

        # 创建姓名输入区域
        ttk.Label(master, text="姓名:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
        self.name_entry = ttk.Entry(master, width=30)
        self.name_entry.grid(row=0, column=1, padx=5, pady=5)

        # 创建年龄输入区域
        ttk.Label(master, text="年龄:").grid(row=1, column=0, padx=5, pady=5, sticky="w")
        self.age_entry = ttk.Entry(master, width=30)
        self.age_entry.grid(row=1, column=1, padx=5, pady=5)

        # 返回初始焦点所在的部件
        return self.name_entry

    def buttonbox(self):
        """自定义按钮布局"""
        # 创建按钮容器
        box = ttk.Frame(self)

        # 确认按钮
        ok_btn = ttk.Button(box, text="确认", width=10, command=self.ok)
        ok_btn.pack(side="left", padx=5, pady=10)

        # 取消按钮
        cancel_btn = ttk.Button(box, text="取消", width=10, command=self.cancel)
        cancel_btn.pack(side="left", padx=5, pady=10)

        # 绑定Enter键触发确认
        self.bind("<Return>", self.ok)
        # 绑定Escape键触发取消
        self.bind("<Escape>", self.cancel)

        box.pack()

    def apply(self):
        """处理用户输入的数据"""
        self.name = self.name_entry.get().strip()
        self.age = self.age_entry.get().strip()


if __name__ == "__main__":
    root = tk.Tk()
    root.title("自定义对话框示例")
    root.geometry("400x200")

    # 显示提示信息的标签
    result_label = ttk.Label(root, text="请点击按钮打开对话框", font=("SimHei", 12))
    result_label.pack(pady=50)


    def open_dialog():
        """打开自定义对话框并显示结果"""
        dialog = CustomDialog(root, "请输入个人信息")
        # 如果用户点击了确认且输入了内容
        if dialog.name or dialog.age:
            result = f"姓名: {dialog.name}\n年龄: {dialog.age}"
            result_label.config(text=result)


    # 打开对话框的按钮
    ttk.Button(root, text="打开对话框", command=open_dialog).pack(pady=10)

    root.mainloop()
